package com.itheima.aop;

import com.itheima.anno.LogAnnotation;
import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect
@Slf4j
@Component
public class OperationLogAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;

    //环绕通知
    /*@Around( "(execution(* com.itheima.controller.*.insert*(..)) || " +
            " execution(* com.itheima.controller.*.delete*(..)) || " +
            " execution(* com.itheima.controller.*.update*(..)))")
    */
    @Around("@annotation(log)")
    public Object  around(ProceedingJoinPoint joinPoint, LogAnnotation log) throws Throwable {
        // 记录开始时间
        long startTime = System.currentTimeMillis();
        // 执行方法
        Object result = joinPoint.proceed();
        // 当前时间
        long endTime = System.currentTimeMillis();
        // 耗时
        long costTime = endTime - startTime;

        // 构建日志对象
        OperateLog operateLog = new OperateLog();
        operateLog.setOperateEmpId(getCurrentUserId()); // 需要实现 getCurrentUserId 方法
        operateLog.setOperateTime(LocalDateTime.now());
        operateLog.setClassName(joinPoint.getTarget().getClass().getName());
        operateLog.setMethodName(joinPoint.getSignature().getName());
        operateLog.setMethodParams(Arrays.toString(joinPoint.getArgs()));
        operateLog.setReturnValue(result.toString());
        operateLog.setCostTime(costTime);

        // 插入日志
        operateLogMapper.insertOperateLog(operateLog);
        return result;
    }

    private Integer getCurrentUserId() {
        //设置id的地方是设置调用生成token的地方，就是登录的地方
        //获取当前线程
        Integer id = CurrentHolder.getCurrentId();
        // 清空当前线程绑定的id
        CurrentHolder.remove();
        return id;
    }

}
